//
//  HMQuestionCell.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/17.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

// 提问的表单
class HMQuestionCell: HMTableViewCell {
    public var cellHeight: CGFloat = 0.0
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     class func cell(json: JSON, tableView: UITableView, cellForRowAt indexPath: IndexPath) -> HMQuestionCell {
        let identifier = "HMQuestionCell"
        var cell: HMQuestionCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? HMQuestionCell
        if cell == nil {
            cell = HMQuestionCell.init(style: .default, reuseIdentifier: identifier)
        }
        
        
        cell?.setupViews(json: json, tableView: tableView, view: (cell?.contentView)!, indexPath: indexPath)
        cell?.selectionStyle = UITableViewCellSelectionStyle.none
        return cell!
    }
    
    func setupViews(json: JSON, tableView: UITableView, view: UIView, indexPath: IndexPath) {
        
        let matter = UILabel()
        let edit = UIButton()
        let viewLine = UIView() //分割线
        
        let head = TitleHead(self, addView: matter)
        head.setJson(json: ["describe": json["describe"].stringValue])
        view.addSubview(head)
        view.addSubview(edit)
        view.addSubview(viewLine)
//        view.backgroundColor = .red
        
        matter.centerYAlign(view: head)
        matter.text = json["value"].stringValue
        matter.trailingAlign(view: view)
        

        let lists = QuestionListsView()
        view.addSubview(lists)
        let listsItem = lists.setViews(json: ["ary" : ["如何实现文件在线高清预览？个人觉得应该是将文件转为HTML格式，可是怎么转比如用js的什么方法或框架？或者其他什么技术组合？是否高清，各有什么优缺点？", "333333333333"]], self, deleteClick: #selector(deleteBtnClick))
                lists.topVertically(view: head)
                lists.leadingAlign(view: view)
                lists.trailingAlign(view: view)
//                lists.backgroundColor = .blue
                lists.heightConstrain(predicate: "\(listsItem.height)")
        
        
        edit.topVertically(view: lists)
        edit.trailingAlign(view: view)
        edit.heightConstrain(predicate: "\(44)")
        edit.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        edit.setTitle("点击编辑", for: .normal)
        
        
        
        let btn = BtnRLView()
        view.addSubview(btn)
        let btnItem = btn.setViews(json: nil, self, lSelector: #selector(buyBtnClick), rSelector:  #selector(addBtnClick))
        btn.topVertically(view: edit)
        btn.leadingAlign(view: view)
        btn.trailingAlign(view: view)
        btn.heightConstrain(predicate: "\(btnItem.1)")
        
        
        viewLine.backgroundColor = configure.shareConfigure.HMColor3
        viewLine.topVertically(view: btn)
        viewLine.leadingAlign(view: view, predicate: "0")
        viewLine.trailingAlign(view: view, predicate: "0")
        viewLine.heightConstrain(predicate: "\(1.0)")
        
        cellHeight = 44.0 + 8.0 + 44 + 8.0 + (btnItem.1 + 8.0) + listsItem.height + 9.0//btnItem.1//con.top= 8
    }
    
    @objc func buyBtnClick(sender: UIButton) {
        print("-----一键购买", sender)
    }
    @objc func addBtnClick(sender: UIButton) {
        print("-----添加提醒", sender)
    }
    @objc func deleteBtnClick(sender: UIButton) {
        print("-----删除", sender)
    }
    
//    override func setupViews(view: UIView) {
//
//    }
    
}


class QuestionListsView: UIView {
    var topH: CGFloat = 0.0
    var itemH: CGFloat = 0.0
    var isHiddenDeleteBtn: Bool = false
    private let height: CGFloat = 40.0
    
    func setViews(json: JSON, _ target: Any?, deleteClick: Selector) -> ( top: CGFloat, height: CGFloat) {
        
        
        if json != JSON.null {
            let ary = json["ary"].arrayValue
            var i = 0
            let rect = self.calculateSize(json: json["ary"], font: 18)
            
            itemH = rect.heights + CGFloat(ary.count) * 10.0 //(偏差值 2左右 )
            for item in ary {
                let l1 = UILabel()
                let deleteBtn = UIButton()
                self.addSubview(deleteBtn)
                self.addSubview(l1)
                topH =  (i != 0) ? rect.ary[i-1].height + 10.0 : 0  //* CGFloat(i)
//                if i == 1 {
//                    l1.backgroundColor = .yellow
//                }else {
//                    l1.backgroundColor = .red
//                }
              
                l1.text = "\(i+1)、" + item.stringValue
                l1.font = UIFont.systemFont(ofSize: 18)
//                l1.lineBreakMode = NSLineBreakMode.byTruncatingTail
                l1.numberOfLines = 0
                let emptylen: CGFloat  = l1.font.pointSize * 1
                     l1.attributedText = l1.text?.firstLineIndent(length: emptylen)
//                 let size :CGSize  = l1.sizeThatFits(CGSize.init(width: configure.shareConfigure.screenWidth - 32, height: configure.shareConfigure.screenHeight))
                
                l1.topAlign(view: self, predicate: "\(topH)")
                l1.leadingAlign(view: self)
//                 l1.trailingAlign(view: self)
                l1.heightConstrain(predicate: "\(rect.ary[i].height + 10.0)")
                l1.addLayer(isAddLayer: (false, false, false, true), color: configure.shareConfigure.HMColor2, crude: 1, layout: (w: configure.shareConfigure.screenWidth - 32, h: rect.ary[i].height + 10.0))
                
                
                if(isHiddenDeleteBtn == false) {
                    deleteBtn.centerYAlign(view: l1)
                    deleteBtn.trailingAlign(view: self)
                    deleteBtn.leadingHorizontally(view: l1)
                    deleteBtn.widthConstrain(predicate: "20")
                    deleteBtn.heightConstrain(predicate: "20")
                    deleteBtn.setImage(UIImage.init(named: "trash"), for: UIControlState.normal)
                    deleteBtn.tag = i
                    deleteBtn.addTarget(target, action: deleteClick, for: UIControlEvents.touchUpInside)
                }else {
                    
                }
               i += 1
            }
            
            
        }
        
        return (topH, itemH)
    }
    func calculateSize(json: JSON, font: CGFloat) ->  (ary: [CGSize], heights: CGFloat){
        var i = 0
        var heights: CGFloat = 0.0
        var arySizes: [CGSize] = []
        for item in json.arrayValue {
            let str = item.stringValue
            let rect = String.getTextRectSize(text: str as NSString, font: font, size: CGSize.init(width: configure.shareConfigure.screenWidth - 32, height: configure.shareConfigure.screenHeight))
            
            arySizes.append(rect)
            heights += rect.height
            i += 1
        }
   
        return (arySizes, heights)
    }
    
}

extension String {
    /// 首行缩进
    func firstLineIndent(length: CGFloat) -> NSAttributedString {
        let paragraphStyle = NSParagraphStyle()
        paragraphStyle.setValue(length, forKey: "firstLineHeadIndent")
        let attributedText = NSAttributedString(string: self,
                                                attributes: [.paragraphStyle : paragraphStyle])
        return attributedText
    }
    
}

